import 'package:flutter/material.dart';
import 'package:flutter_uxin/addressBook/addressBookManager.dart';
import 'package:flutter_uxin/addressBook/Parsers/commonAddressBook.dart';
import 'package:flutter_uxin/Compontents/DB/DBManager.dart';

import 'package:flutter_uxin/Tools/config/commonTool.dart';
import 'package:flutter_uxin/Tools/Define/Device.dart';

class addressBookPage extends StatefulWidget {
  addressBookPage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _addressBookPageState createState() => _addressBookPageState();
}

class _addressBookPageState extends State<addressBookPage> {
//  List<int> mList; //组成一个int类型数组，用来控制索引
//  List<ExpandStateBean> expandStateList; //开展开的状态列表,ExpandStateBean是自定义的类

  var _futureBuilderFuture;

  void initState() {
    super.initState();
    _futureBuilderFuture =
        DBManager.shared().getGroupsWithOutGroupTypeList('GG,CG');
  }

  //当整个页面dispose时，记得把控制器也dispose掉，释放内存
  @override
  void dispose() {
    super.dispose();
  }
  //构造方法，调用这个类的时候自动执行
//  _addressBookPageState() {
//
//    mList = new List();
//    expandStateList = new List();
//    //遍历两个List进行赋值
//    for (int i = 0; i < 19; i++) {
//      mList.add(i);
//      expandStateList.add(ExpandStateBean(i, false)); //item初始状态为闭着的
//    }
//  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.cloud_download),
            onPressed: () {
              print("cloud_download");
              addressBookManager.getInstance().tryUpdateAddress();
            },
          ),
        ],
      ),
      body: FutureBuilder(
        future: _futureBuilderFuture,
        builder: _buildFuture,
      ),
    );
  }

  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        print('还没有开始网络请求');
        return Text('还没有开始网络请求');
      case ConnectionState.active:
        print('active');
        return Text('ConnectionState.active');
      case ConnectionState.waiting:
        print('waiting');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        print('done');
        if (snapshot.hasError) {
          return Text('Error: ${snapshot.error}');
        }

        List resList = snapshot.data;
        print('resList---------------$resList');
        if (resList is List && resList.length > 0) {
          return GroupExpansionPanelList(resList);
        }
//        print('snapshot---------------$snapshot');
//        print('snapshot---------------$res');
        return Container();
      default:
        return null;
    }
  }
}

//list中item状态自定义类
class ExpandStateBean {
  var isOpen; //item是否打开
  var index; //item中的索引
  Groups groups;
  ExpandStateBean(this.index, this.isOpen, this.groups);
}

class GroupExpansionPanelList extends StatefulWidget {
//  areaListPage({Key key, this.areaList ,this.onTap}) : super(key: key);

  @required
  ValueChanged<Members> onTap;
  final List<Groups> groupsList;
  //当整个页面dispose时，记得把控制器也dispose掉，释放内存
  GroupExpansionPanelList(this.groupsList, {this.onTap});

  @override
  _GroupExpansionPanelListState createState() =>
      _GroupExpansionPanelListState();
}

class _GroupExpansionPanelListState extends State<GroupExpansionPanelList> {
  List<ExpandStateBean> expandStateList; //开展开的状态列表,ExpandStateBean是自定义的类

  void initState() {
    super.initState();

//    print('initState-------------');
    expandStateList = new List();
    //遍历List进行赋值
    for (int i = 0; i < widget.groupsList.length; i++) {
      Groups groups = widget.groupsList[i];
      if (groups != null && groups is Groups) {
        expandStateList.add(
            ExpandStateBean(i, false, widget.groupsList[i])); //item初始状态为闭着的
      }
    }
  }

  //当整个页面dispose时，记得把控制器也dispose掉，释放内存
  @override
  void dispose() {
    super.dispose();
  }

//  //构造方法，调用这个类的时候自动执行
//  _GroupExpansionPanelListState() {
//
//
//  }

//修改展开与闭合的内部方法
  _setCurrentIndex(int index, isExpand) {
    setState(() {
      //遍历可展开状态列表
      expandStateList.forEach((item) {
        if (item.index == index) {
          //取反，经典取反方法
          item.isOpen = !isExpand;
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return new SingleChildScrollView(
      child: ExpansionPanelList(
        //交互回调属性，里面是个匿名函数
        expansionCallback: (index, bol) {
          //调用内部方法
          _setCurrentIndex(index, bol);
        },
        //进行map操作，然后用toList再次组成List
        children: expandStateList.asMap().keys.map((index) {
          //返回一个组成的ExpansionPanel
          return ExpansionPanel(
              headerBuilder: (context, isExpanded) {
                return ListTile(
                  title: Text('  ${expandStateList[index].groups.name}'),
                );
              },
              body: userList(expandStateList[index].groups.members),
              isExpanded: expandStateList[index].isOpen);
        }).toList(),
      ),
    );
  }
}

class userList extends StatelessWidget {
//  areaListPage({Key key, this.areaList ,this.onTap}) : super(key: key);
  userList(this.membersList, {this.onTap});

  @required
  ValueChanged<Members> onTap;
  final List<Members> membersList;
  //当整个页面dispose时，记得把控制器也dispose掉，释放内存

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: membersList.length == null ? 0 : membersList.length,
        separatorBuilder: (BuildContext context, int index) =>
            Divider(color: Colors.grey), //index为偶数，创建绿色分割线；index为奇数，则创建红色分割线
//             itemBuilder: (BuildContext context, int index) => ListTile(
//              title: Text("${membersList[index].realName}"),
//              onTap: () {
//                Members member = membersList[index];
//                print('realName-------------${member.name}');
////            onTap(member);
//              },
//            ) //创建子Widget

        itemBuilder: (BuildContext context, int index) => addressItemWidget(
              "${membersList[index].headerImageUrl}",
              "${membersList[index].realName}",
              "${membersList[index].mobile}",
              beganChat: () {
                print('userID-------------${membersList[index].id}');
                Navigator.of(context).pushNamed(
                  "chatScreen",
                );
              },
              callUserPhone: () {
                print('phoneNumber-------------${membersList[index].mobile}');
                Device.call(membersList[index].mobile);
              },
            ));
  }
}

class addressItemWidget extends StatelessWidget {
  final String headPortrait;
  final String name;
  final String mobile;
//  @required VoidCallback onTap;

  VoidCallback beganChat;
  VoidCallback callUserPhone;

  addressItemWidget(this.headPortrait, this.name, this.mobile,
      {this.beganChat, this.callUserPhone});

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(
      children: <Widget>[
        Container(
          color: Colors.white,
          height: 53,
          child: _addressItem(this.headPortrait, this.name, this.mobile,
              beganChat: this.beganChat, callUserPhone: this.callUserPhone),
        ),
//        Container(
//          color: Color(0xffeaeaea),
//          constraints: BoxConstraints.expand(height: 1.0),
//        ),
      ],
    ));
  }

  Widget _addressItem(String imageName, String title, String mobile,
      {VoidCallback beganChat, VoidCallback callUserPhone}) {
    return InkWell(
      onTap: () {
        this.beganChat();
      },
      child: Row(
        children: _addressItemRowList(imageName, title, mobile,
            beganChat: beganChat, callUserPhone: callUserPhone),
      ),
    );
  }

  Future<String> getRequestUrl(String extendUrl) async {
    if (extendUrl != null && (extendUrl is String) && extendUrl.length > 0) {
      String headPortrait = await commonTool.getHeadPortrait(extendUrl);
      return headPortrait;
    } else {
      return '';
    }
  }

  Widget _IMGBuildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        print('还没有开始网络请求');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.active:
        print('active');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.waiting:
        print('waiting');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        print('done');
        if (snapshot.hasError) {
          return Image.asset(
            'RootResource/images/logo_uxin.png',
            width: 30,
            height: 30,
          );
        }

        String imgURL = snapshot.data;

        if (imgURL is String && imgURL.length > 0) {
          print('imgURL---------------$imgURL');
          return FadeInImage.assetNetwork(
            placeholder: 'RootResource/images/logo_uxin.png', //占位图
            image: imgURL,
            fit: BoxFit.cover, //图片拉伸模式
            width: 30,
            height: 30,
          );
        }
//        print('snapshot---------------$snapshot');
//        print('snapshot---------------$res');
        return Container();
      default:
        return null;
    }
  }

  List<Widget> _addressItemRowList(
      String imageName, String title, String mobile,
      {VoidCallback beganChat, VoidCallback callUserPhone}) {
    List<Widget> rowList = new List();
    //头像
    rowList.add(Expanded(
      flex: 1,
      child: Container(
        padding: EdgeInsets.only(left: 16),
        child: FutureBuilder(
          future: getRequestUrl(imageName),
//          future: getRequestUrl('areaDNS_download_url',imageName),
          builder: _IMGBuildFuture,
        ),
      ),
    ));
//名称
    rowList.add(Expanded(
      flex: 6,
      child: Container(
        padding: EdgeInsets.only(left: 10),
        child: Text(
          title,
          style: TextStyle(fontSize: 16),
        ),
      ),
    ));

    if (beganChat != null) {
      //聊天
      rowList.add(Expanded(
        flex: 1,
        child: Container(
            child: IconButton(
          icon: Icon(
            Icons.mode_comment,
            size: 20,
            color: Color(0xFF80D8FF),
          ),
          onPressed: () {
            this.beganChat();
          },
        )),
      ));
    }

    if (callUserPhone != null &&
        mobile != null &&
        (mobile is String) &&
        mobile.length > 0) {
      //打电话
      rowList.add(Expanded(
        flex: 1,
        child: Container(
            child: IconButton(
          icon: Icon(
            Icons.phone,
            size: 20,
            color: Color(0xFF80D8FF),
          ),
          onPressed: () {
            this.callUserPhone();
          },
        )),
      ));
    } else {
      //打电话
      rowList.add(Expanded(
        flex: 1,
        child: Container(
            child: IconButton(
          icon: Icon(
            Icons.phone_locked,
            size: 20,
            color: Colors.grey,
          ),
          onPressed: () {
            this.callUserPhone();
          },
        )),
      ));
    }

    return rowList;
  }
}
